package be.fomp.jeve.model.data.standard.skilltree;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;

import be.fomp.jeve.core.exceptions.JEveException;
import be.fomp.jeve.model.data.AbstractResultImpl;
import be.fomp.jeve.model.data.standard.SkillTree.Group;

public final class SkillTreeImpl extends AbstractResultImpl implements SkillTreeTemplate{
	static final long serialVersionUID = 1L;
	
	private Map<Integer,Group> groups = new HashMap<Integer, Group>();
	
	@SuppressWarnings("unchecked")
	public SkillTreeImpl(Document xmlDocument) throws JEveException{
		super(xmlDocument);
		
		Element root = xmlDocument.getRootElement();
		
		List<Element> resultSet = root.getChild("result").getChild("rowset").getChildren();
		
		for(Element groupElement: resultSet) {
			Integer groupId = Integer.valueOf(groupElement.getAttributeValue("groupID"));
			Group group = new GroupImpl(groupId, groupElement);
			this.groups.put(groupId, group);
		}
	}
	
	public Collection<Group> getGroups(){
		return this.groups.values();
	}
	
	public Group getGroupById(Integer groupId) {
		return this.groups.get(groupId);
	}
	
	public Group getGroupByName(String groupName) {
		Group returnValue = null;
		
		for(Group g: getGroups()){
			if(groupName.equals(g.getGroupName())){
				returnValue = g;
				break;
			}
		}
		
		return returnValue;
	}
	
	public void writeObject(ObjectOutputStream os) {
		try {
			os.defaultWriteObject();
			os.writeObject(this.groups);
		} catch (Exception e) { e.printStackTrace();  }
	}

	@SuppressWarnings("unchecked")
	public void readObject (ObjectInputStream is) {
		try {
			is.defaultReadObject();
			this.groups = ((Map<Integer, Group>)is.readObject());
		} catch (Exception e) {e.printStackTrace();}
	}
}
